﻿using System;
using System.Configuration;
using System.Text;
using NLog;

namespace Softio.Mscd
{
    public static class HandlerConfig
    {

        private static Logger logger = LogManager.GetCurrentClassLogger();

        public static TimeSpan DefaultCacheDuration = TimeSpan.FromDays(30);

        public static string RootDirectory = "";

        public static Encoding FilesEncoding = Encoding.UTF8;
        public static int ExpiredDays = 0;
        
        public static string[] FileTypes =
            new string[] { ".CSS", ".JS", ".HTML", ".HTM", ".PNG", ".JPEG", ".JPG", ".GIF", ".BMP", ".SWF", ".TXT" };

        public static string[] CompressFileTypes =
            new string[] { ".CSS", ".HTML", ".HTM" };


        public static bool UseMustRevalidateHeader = false;

        public static void Configure()
        {
            logger.Trace("MSCD Starting load configuration...");
            string exp = ConfigurationManager.AppSettings["MSCD.ExpiredInDays"];
            int expi;
            if (int.TryParse(string.IsNullOrEmpty(exp) ? "0" : exp, out expi))
            {
                ExpiredDays = expi;
                logger.Trace("'MSCD.ExpiredInDays' configured as: {0}", expi);
            }
            else
            {
                logger.Trace("'MSCD.ExpiredInDays' configured as default: {0}", ExpiredDays);
            }

            string enc = ConfigurationManager.AppSettings["MSCD.ContentEncoding"];
            if (enc != null)
            {
                try
                {
                    FilesEncoding = Encoding.GetEncoding(enc);
                    logger.Trace("'MSCD.ContentEncoding' configured as: {0}", FilesEncoding.WebName);
                }
                catch
                {
                    FilesEncoding = Encoding.UTF8;
                    logger.Trace("'MSCD.ExpiredInDays' configured as default: {0}", FilesEncoding.WebName);
                }
            }
            else
            {
                logger.Trace("'MSCD.ExpiredInDays' configured as default: {0}", FilesEncoding.WebName);
            }

            string allowedFileTypes = ConfigurationManager.AppSettings["MSCD.AllowedFileTypes"];
            if (!string.IsNullOrEmpty(allowedFileTypes))
            {
                FileTypes = allowedFileTypes.ToUpperInvariant().Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                logger.Trace("'MSCD.AllowedFileTypes' configured as: '{0}'", allowedFileTypes);
            }
            else
            {
                logger.Trace("'MSCD.AllowedFileTypes' configured as default: '{0}'", string.Join(", ", FileTypes));
            }

            string compresedFileTypes = ConfigurationManager.AppSettings["MSCD.CompressedFileTypes"];
            if (!string.IsNullOrEmpty(compresedFileTypes))
            {
                CompressFileTypes = compresedFileTypes.ToUpperInvariant().Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                logger.Trace("'MSCD.CompressedFileTypes' configured as: '{0}'", compresedFileTypes);
            }
            else
            {
                logger.Trace("'MSCD.CompressedFileTypes' configured as default: '{0}'", string.Join(", ", CompressFileTypes));
            }

            RootDirectory = (ConfigurationManager.AppSettings["MSCD.RootDirectory"] ?? "").Replace("\\", "/");
            if (RootDirectory.Length > 0)
            {
                if (RootDirectory.StartsWith("/"))
                {
                    RootDirectory = RootDirectory.Remove(0, 1);
                }
                if (!RootDirectory.EndsWith("/"))
                {
                    RootDirectory = RootDirectory + "/";
                }
            }

            string useMustRevalidateHeader = ConfigurationManager.AppSettings["MSCD.UseMustRevalidateHeader"];
            if (!string.IsNullOrEmpty(useMustRevalidateHeader) && useMustRevalidateHeader.Equals("true", StringComparison.OrdinalIgnoreCase))
            {
                UseMustRevalidateHeader = true;
                logger.Trace("'MSCD.UseMustRevalidateHeader' configured as: '{0}'", compresedFileTypes);
            }
            else
            {
                logger.Trace("'MSCD.UseMustRevalidateHeader' configured as default: '{0}'", UseMustRevalidateHeader);
            }

            Array.Sort(FileTypes);
            Array.Sort(CompressFileTypes);

            logger.Trace("MSCD Configuration loaded.");
        }
    }
}
